<?php

namespace App\Console\Commands;

use App\Models\Company;
use App\MongoTypeFix;
use App\Plugins\Plugin;
use Illuminate\Console\Command;

class CachePlugin extends Command
{
    use MongoTypeFix;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'plugin:cache';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Cache plugin\'s alias';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $plugin = new Plugin();
        //获取所有使用插件且有二级域名的公司
        $companies = Company::where([
            '$and' => [
                self::notEmpty('options.plugins'),
                self::notEmpty('alias')
            ]
        ])->get();
        //每个插件对应有哪些公司使用
        $plugin_alias = $companies->reduce(function($result, $item) {
            foreach ($item->options['plugins'] as $plugin) {
                $result[$plugin][] = $item->alias;
            }
            return $result;
        });
        //将插件二级域名依次写入文件
        array_walk($plugin_alias, function($alias, $pluginName) use ($plugin) {
            if ($plugin->findByName($pluginName)) {
                foreach ($alias as $item) {
                    $plugin->register(ucfirst($pluginName), $item);
                }
            }
        });
    }
}
